package com.digitalchina.dcn.dscc.portal.server;

import com.digitalchina.dcn.dscc.portal.client.PortalClient;
import com.digitalchina.dcn.dscc.portal.protocol.PortalMessage;
import com.digitalchina.dcn.dscc.portal.util.PortalUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.apache.spark.network.protocol.Message;
import org.apache.spark.network.server.TransportChannelHandler;
import org.apache.spark.network.util.NettyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.digitalchina.dcn.dscc.portal.protocol.PortalMessage.*;

/**
 * Created by Administrator on 2016/8/23 0023.
 */
public class PortalChannelHandler extends SimpleChannelInboundHandler<PortalMessage> {

    private final Logger logger = LoggerFactory.getLogger(PortalChannelHandler.class);

    private PortalMessageHandler responseHandler;

    public PortalChannelHandler( PortalMessageHandler messageHandler) {

        responseHandler = messageHandler;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, PortalMessage msg) throws Exception {
        responseHandler.handle(msg);
//        Type type = msg.type();
//        switch (type) {
//            case ChallengeAck:
//                processChallengeAck(msg);
//                break;
//            case AuthAck:
//                processAuthAck(msg);
//                break;
//            case LogoutAck:
//                processLogoutAck(msg);
//            default:
//                logger.warn("error portal response message type from AC! type = " + type.name());
//        }

    }

//    private void processAuthAck(PortalMessage msg) {
//    }
//
//    private void processLogoutAck(PortalMessage msg) {
//
//    }
//
//    private void processChallengeAck(PortalMessage msg) {
//
//    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.warn("Exception in connection from " + ctx.channel().localAddress(),
                cause);
        responseHandler.exceptionCaught(cause);
        ctx.close();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        try {
            responseHandler.channelActive();
        } catch (RuntimeException e) {
            logger.error("Exception from request handler while registering channel", e);
        }

        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        try {
            responseHandler.channelInactive();
        } catch (RuntimeException e) {
            logger.error("Exception from response handler while unregistering channel", e);
        }

        super.channelInactive(ctx);
    }
}
